import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingWorker;

import watki.ManagerWatkow;
import algorytmy.Algorytmy;


public class Okno {

	private JFrame frame;
	private JTextField textField;
	private File wybranyPlik;
	private JTextPane text;
	JButton btnZapiszWyniki;
	private JLabel label;
	private String wczytanyText;
	private JComboBox<Algorytmy> comboBox;
	StringBuilder plainText = new StringBuilder();
	StringBuilder tekstBuilder = new StringBuilder();
	JButton btnSzukaj;
	JButton btnOtworz;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Okno window = new Okno();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public Okno() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	public void szukaj(){

		TreeSet<Integer> lista = new TreeSet<Integer>();
		String szukany = textField.getText();
		tekstBuilder = new StringBuilder(wczytanyText);
		
		ManagerWatkow manager = ManagerWatkow.manager();
		
		try {
			lista = manager.start((Algorytmy)comboBox.getSelectedItem(), szukany, plainText.toString(), 2);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		StringBuilder wyswietlany = new StringBuilder(plainText);
		int wskaznik = 0;
		for(int i: lista){
			
			wyswietlany.insert(i+wskaznik, "<b>");
			wskaznik += 3;
			wyswietlany.insert(i+szukany.length()+wskaznik, "</b>");
			wskaznik += 4;
		}
	
		text.setContentType("text/html");
		//text.setText("<html><head>" +
		// 		"<style>b{background-color:yellow;font-size:16px;}body{font-family:Calibri;}</style>" +
		//   		"<body>"+tekstBuilder.toString());
		
		Pattern pattern = Pattern.compile("\r");
		
		
		Matcher matcher = pattern.matcher(wyswietlany);
		while(matcher.find()){
			int ind =  matcher.start();
			//System.out.println(ind);
			wyswietlany.replace(ind, ind+1, "<br/>");
		}
		
		wczytanyText = wyswietlany.toString();
		

}
	
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 800, 600);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		textField = new JTextField();
		textField.setBounds(105, 11, 214, 20);
		frame.getContentPane().add(textField);
		textField.setColumns(10);
		
		textField.addKeyListener(new KeyListener(){

		
			@Override
			public void keyTyped(KeyEvent arg0) {
				// TODO Auto-generated method stub
				if(arg0.getKeyChar()==KeyEvent.VK_ENTER){
					SwingWorker worker = new SwingWorker<Integer, Void>() {
						
						
					    @Override
					    public Integer doInBackground() {
					    	
					    	label.setText("Wyszukiwanie...");
					    	comboBox.setEnabled(false);
					    	btnSzukaj.setEnabled(false);
							btnOtworz.setEnabled(false);
							btnZapiszWyniki.setEnabled(false);
							textField.setEnabled(false);
							text.setEnabled(false);
					    	szukaj();
					    	return 1;
					    }

					    @Override
					    public void done() {
					    	comboBox.setEnabled(true);
					    	text.setEnabled(true);
					    	textField.setEnabled(true);
					    	btnSzukaj.setEnabled(true);
							btnOtworz.setEnabled(true);
							btnZapiszWyniki.setEnabled(true);
					    	label.setText("Wczytany plik: "+wybranyPlik);
					    	text.setContentType("text/html");
							text.setText("<html><head>" +
							 		"<style>b{background-color:yellow;font-size:16px;}body{font-family:Calibri;}</style>" +
							   		"<body>"+wczytanyText);
							
							
					    }
					};
					 worker.execute();
				}
					
			}

			@Override
			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void keyReleased(KeyEvent e) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		JLabel lblWzorzec = new JLabel("Wzorzec:");
		lblWzorzec.setBounds(10, 14, 85, 14);
		frame.getContentPane().add(lblWzorzec);
		
		btnSzukaj = new JButton("Szukaj");
		btnSzukaj.setBounds(560, 10, 89, 23);
		frame.getContentPane().add(btnSzukaj);
		btnSzukaj.addActionListener(new SzukajListener()
				);
		
		btnOtworz = new JButton("Otw\u00F3rz plik");
		btnOtworz.addActionListener(new OtworzListener()
		);
		btnOtworz.setBounds(659, 10, 115, 23);
		frame.getContentPane().add(btnOtworz);
		
		JSeparator separator = new JSeparator();
		separator.setBounds(10, 536, 622, 2);
		frame.getContentPane().add(separator);
		
		label = new JLabel("Nie wczytano pliku");
		label.setBounds(10, 536, 658, 14);
		frame.getContentPane().add(label);
		
		text = new JTextPane();
		JScrollPane scrollPane = new JScrollPane(text);
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setBounds(10, 42, 764, 483);
		text.setText("Wczytaj plik");
		text.setEditable(false);
		frame.setTitle("Wyszukiwanie wzorca w tekście");
		frame.getContentPane().add(scrollPane);
		
		comboBox = new JComboBox(Algorytmy.values());
	
		comboBox.setBounds(329, 11, 221, 20);
		frame.getContentPane().add(comboBox);
		
		btnSzukaj.setEnabled(false);
		
		btnZapiszWyniki = new JButton("Zapisz wyniki");
		btnZapiszWyniki.setEnabled(false);
		btnZapiszWyniki.setBounds(643, 532, 131, 23);
		btnZapiszWyniki.addActionListener(new ZapiszListener());
		frame.getContentPane().add(btnZapiszWyniki);
	}
	
	private class ZapiszListener implements ActionListener{
		File wybrany;
		@Override
		public void actionPerformed(ActionEvent arg0) {
			JFileChooser chooser = new JFileChooser();
			
			int result = chooser.showSaveDialog(frame);
			if(result != -1){
				wybrany = chooser.getSelectedFile();
				try {
					PrintWriter out = new PrintWriter(wybrany);
					out.print(ManagerWatkow.getWynik().toString());
					
					out.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
				
		}
	}
	
	private class SzukajListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			SwingWorker worker = new SwingWorker<Integer, Void>() {
				
				
			    @Override
			    public Integer doInBackground() {
			    	
			    	label.setText("Wyszukiwanie...");
			    	comboBox.setEnabled(false);
			    	btnSzukaj.setEnabled(false);
					btnOtworz.setEnabled(false);
					btnZapiszWyniki.setEnabled(false);
					textField.setEnabled(false);
					text.setEnabled(false);
			    	szukaj();
			    	return 1;
			    }

			    @Override
			    public void done() {
			    	comboBox.setEnabled(true);
			    	text.setEnabled(true);
			    	textField.setEnabled(true);
			    	btnSzukaj.setEnabled(true);
					btnOtworz.setEnabled(true);
					btnZapiszWyniki.setEnabled(true);
			    	label.setText("Wczytany plik: "+wybranyPlik);
			    	text.setContentType("text/html");
					text.setText("<html><head>" +
					 		"<style>b{background-color:yellow;font-size:16px;}body{font-family:Calibri;}</style>" +
					   		"<body>"+wczytanyText);
					
					
			    }
			};
			 worker.execute();
			
		}
		
		
	}
	
	
		private class OtworzListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			WyborPliku oknoDialogowe = new WyborPliku();
			oknoDialogowe.showOpenDialog(frame);
			wybranyPlik = oknoDialogowe.getSelectedFile();
			wczytanyText="";
			tekstBuilder = new StringBuilder();
			if(wybranyPlik != null){
				//jesli wczytano jakis plik to odpalany w tle dzialania
				label.setText("Wczytywanie pliku...");
				comboBox.setEnabled(false);
		    	btnSzukaj.setEnabled(false);
				btnOtworz.setEnabled(false);
				btnZapiszWyniki.setEnabled(false);
				textField.setEnabled(false);
				text.setEnabled(false);
				
				
				/*******************************************************************/
				SwingWorker worker = new SwingWorker<Integer, Void>() {
					StringBuilder temporal = new StringBuilder();
					
				    @Override
				    public Integer doInBackground() {
				    	try {
							Scanner skaner = new Scanner(wybranyPlik, "cp1250");
							plainText = new StringBuilder();
							String temp;
							
							while(skaner.hasNextLine()){
								temp = skaner.nextLine();
								tekstBuilder.append(temp);
								tekstBuilder.append("\r");
								plainText.append(temp);
								plainText.append("\r");
							}
							
							tekstBuilder.append("</body></html>" );
							Pattern pattern = Pattern.compile("\r");
							Matcher matcher = pattern.matcher(tekstBuilder);
							while(matcher.find()){
								int ind =  matcher.start();
								//System.out.println(ind);
								tekstBuilder.replace(ind, ind+1, "<br/>");
							}
							
							wczytanyText = tekstBuilder.toString();
							
							
						} catch (FileNotFoundException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
				    	return 1;
				    }

				    @Override
				    public void done() {
				    	comboBox.setEnabled(true);
				    	text.setEnabled(true);
				    	textField.setEnabled(true);
				    	btnSzukaj.setEnabled(true);
						btnOtworz.setEnabled(true);
				    	label.setText("Wczytany plik: "+wybranyPlik);
				    	text.setContentType("text/html");
						text.setText("<html><head>" +
						 		"<style>b{background-color:yellow;font-size:16px;}body{font-family:Calibri;}</style>" +
						   		"<body>"+wczytanyText);
						
				    }
				};
				 worker.execute();
				/*******************************************************************/
				
				
				
				
				
			}else{
				label.setText("Nie wybrano pliku!");
			}
			
			
		}

		
	}
}
